var db;
var isCreateDbSuccess;
var contactID;
var previousNATab = "tab1";
var groupBy="category";
var assetID;
var newContactEvent=0;
var editAsset;
// = = = = = = = = = = = = = = = = = = = = Home Page  = = = = = = = = = = = = = = = = = = = =
function onLoad(){

	//document.addEventListener("deviceready", onDeviceReady, true);
	//Open or Create database
	onDeviceReady();
}
function onDeviceReady(){	
	db = window.openDatabase("assettracking","1.0","Asset Tracking",1000000);
	db.transaction(createDatabase,ErrorDB,createDbSuccess);
	t=0;
}
function createDatabase(tx){
	//tx.executeSql('DROP TABLE IF EXISTS ASSET');	
	//tx.executeSql('DROP TABLE IF EXISTS CONTACT');
	tx.executeSql('CREATE TABLE IF NOT EXISTS CONTACT(' +
		'id INTEGER PRIMARY KEY AUTOINCREMENT, ' +
		'firstname TEXT NOT NULL, ' +
		'lastname TEXT NOT NULL, ' +
		'company TEXT NOT NULL, ' +
		'jobtitle TEXT, ' +
		'businessphone TEXT, ' +
		'homephone TEXT, ' +
		'mobilephone TEXT, ' +
		'faxnumber TEXT, ' +
		'street TEXT, ' +
		'city TEXT, ' +
		'state TEXT, ' +
		'country TEXT, ' +
		'note nvarchar(2000))'
	);
	tx.executeSql('CREATE TABLE IF NOT EXISTS ASSET(' +
		'id INTEGER PRIMARY KEY AUTOINCREMENT,' +
		'item TEXT NOT NULL,' +
		'category INTEGER NOT NULL, ' +
		'manufacturer TEXT, ' +
		'model TEXT NOT NULL, ' +
		'acquireddate TEXT NOT NULL, ' +
		'purchaseprice INTEGER NOT NULL, ' +
		'currentvalue INTEGER NOT NULL, ' +
		'condition TEXT NOT NULL, ' +
		'location TEXT NOT NULL, ' +
		'owner INTEGER NOT NULL, ' +
		'retireddate TEXT NOT NULL, ' +
		'comment nvarchar(200),' +
		'FOREIGN KEY (owner) REFERENCES CONTACT(id) )'
	);	
}
function createDbSuccess(){
	//console.log("Open database successed!");
	isCreateDbSuccess=1;
}
function ErrorDB(err){
	alert("Database error!");
	//console.log("Database processing error!" + err.code);
}
// New Contact button is clicked
$("#home_newContactButton").off().on("click",function(){
	//The Create button is clicked
	resetNC();
	if (newContactEvent==0){
		$("#create_contact_button").off().on("click",function(){
			if (isCreateDbSuccess){			
				db.transaction(addNewContact,addNewContactError,addNewContactSuccess);
			}
		});
		//The Cancel button is clicked
		$("#cancel_new_contact_button").off().on("click",function(){		
		});
		newContactEvent=1;
	}
});
// Contact list button is clicked
$("#home_contactListButton").off().on("click",function(){
	//Contact is clicked
	db.transaction(loadContactList,ErrorDB);
});
// New Asset button is clicked
$("#home_newAssetButton").off().on("click",function(){
	previousNATab = "tab1";
	$("#asset_details_tab").removeClass("ui-screen-hidden");
	$("#asset_comments_tab").addClass("ui-screen-hidden");
	
	editAsset = 0;
	ResetNewAsset();
	db.transaction(loadOwner,ErrorDB);
	//Swap between Details tab and Comments tab	
	$("#new_asset_navbar ul li").off().on("click",function(){
		var newNATab = $(this).children("a").attr("data-tab-class");
		$("."+previousNATab).addClass("ui-screen-hidden");
		$("."+newNATab).removeClass("ui-screen-hidden");	
		previousNATab = newNATab;
	});
	//The Add button is clicked (add comment)
	$("#add_comment_btn").off().on("click",function(){
		$("#na_asset_comment_history").append("<p>"+$("#na_asset_new_comment").val()+"</p>");
		$("#na_asset_new_comment").val("");
	});
	//The Create Button is clicked
	$("#create_asset_button").off().on("click",function(){
		if (isCreateDbSuccess){
			previousNATab = "tab1";
			db.transaction(addNewAsset,addNewAssetError,addNewAssetSuccess);
			previousNATab = "tab1";
			$("#asset_details_tab").removeClass("ui-screen-hidden");
			$("#asset_comments_tab").addClass("ui-screen-hidden");
		}
	});	
	//The Cancel button is clicked
	$("#cancel_new_asset_button").off().on("click",function(){
		
	});
});
// Asset list button is clicked
$("#home_assetListButton").off().on("click",function(){
	db.transaction(loadAssetList,ErrorDB);
});
// By Category button is clicked
$("#home_byCategoryButton").off().on("click",function(){
	groupBy='category';
	$("#report_group_select").val('category');
	db.transaction(loadReport,ErrorDB);
});
// By Location button is clicked
$("#home_byLocationButton").off().on("click",function(){
	groupBy='location';
	$("#report_group_select").val('location');
	db.transaction(loadReport,ErrorDB);
});
// By Owner button is clicked
$("#home_byOwnerButton").off().on("click",function(){
	groupBy='owner';
	$("#report_group_select").val('owner');
	db.transaction(loadReport,ErrorDB);
});
// By Retired button is clicked
$("#home_byRetiredButton").off().on("click",function(){
	groupBy='retireddate';
	$("#report_group_select").val('retireddate');
	db.transaction(loadReport,ErrorDB);
});

// = = = = = = = = = = = = = = = = = = = = New Contact Page  = = = = = = = = = = = = = = = = = = = =
//reset the new contact page
function resetNC(){
	$("#nc_fname_input").val("");
	$("#nc_lname_input").val("");
	$("#nc_company_input").val("");
	$("#nc_job_title_input").val("");
	$("#nc_business_phone_input").val("");
	$("#nc_home_phone_input").val("");
	$("#nc_mobile_phone_input").val("");
	$("#nc_fax_number_input").val("");
	$("#nc_street_input").val("");
	$("#nc_city_input").val("");
	$("#nc_state_input").val("");
	$("#nc_country_input").val("");
	$("#nc_note_textarea").val("");
}
//Add a new contact to contact list
function addNewContact(tx){
	tx.executeSql('INSERT INTO CONTACT (firstname,lastname,company,jobtitle,businessphone,homephone,mobilephone,faxnumber,street,city,state,country,note)' +
		' VALUES (' +		
		'"' + $("#nc_fname_input").val() + '",' +
		'"' + $("#nc_lname_input").val() + '",' +
		'"' + $("#nc_company_input").val() + '",' +
		'"' + $("#nc_job_title_input").val() + '",' +
		'"' + $("#nc_business_phone_input").val() + '",' +
		'"' + $("#nc_home_phone_input").val() + '",' +
		'"' + $("#nc_mobile_phone_input").val() + '",' +
		'"' + $("#nc_fax_number_input").val() + '",' +
		'"' + $("#nc_street_input").val() + '",' +
		'"' + $("#nc_city_input").val() + '",' +
		'"' + $("#nc_state_input").val() + '",' +
		'"' + $("#nc_country_input").val() + '",' +
		'"' + $("#nc_note_textarea").val() + '")'		
	);
}
function addNewContactSuccess(){
	$("#cdt_fname_input").val($("#nc_fname_input").val());
	$("#cdt_lname_input").val($("#nc_lname_input").val());
	$("#cdt_company_input").val($("#nc_company_input").val());
	$("#cdt_job_title_input").val($("#nc_job_title_input").val());
	$("#cdt_business_phone_input").val($("#nc_business_phone_input").val());
	$("#cdt_home_phone_input").val($("#nc_home_phone_input").val());
	$("#cdt_mobile_phone_input").val($("#nc_mobile_phone_input").val());
	$("#cdt_fax_number_input").val($("#nc_fax_number_input").val());
	$("#cdt_street_input").val($("#nc_street_input").val());
	$("#cdt_city_input").val($("#nc_city_input").val());
	$("#cdt_state_input").val($("#nc_state_input").val());
	$("#cdt_country_input").val($("#nc_country_input").val());
	$("#cdt_note_textarea").val($("#nc_note_textarea").val());
	
	db.transaction(LoadMaxCID,ErrorDB);
	
	$("#edit_contact_button").off().on("click",function(){		
		$("#ec_fname_input").val($("#cdt_fname_input").val());
		$("#ec_lname_input").val($("#cdt_lname_input").val());
		$("#ec_company_input").val($("#cdt_company_input").val());
		$("#ec_job_title_input").val($("#cdt_job_title_input").val());
		$("#ec_business_phone_input").val($("#cdt_business_phone_input").val());
		$("#ec_home_phone_input").val($("#cdt_home_phone_input").val());
		$("#ec_mobile_phone_input").val($("#cdt_mobile_phone_input").val());
		$("#ec_fax_number_input").val($("#cdt_fax_number_input").val());
		$("#ec_street_input").val($("#cdt_street_input").val());
		$("#ec_city_input").val($("#cdt_city_input").val());
		$("#ec_state_input").val($("#cdt_state_input").val());
		$("#ec_country_input").val($("#cdt_country_input").val());
		$("#ec_note_textarea").val($("#cdt_note_textarea").val());
	});
	$("#save_contact_button").off().on("click",function(){
		db.transaction(SaveContact,SaveContactError,SaveContactSuccess);
	});
	$("#dc_yes_button").off().on("click",function(){
		db.transaction(deleteContact,deleteCtError,deleteCtSuccess);
	});
	$("#save_contact_button").off().on("click",function(){
		db.transaction(SaveContact,SaveContactError,SaveContactSuccess);
	});
	$("#dc_yes_button").off().on("click",function(){
		db.transaction(deleteContact,deleteCtError,deleteCtSuccess);
	});
}
function addNewContactError(err){
	alert("Add new contact failed\n" + err.message);
}
function LoadMaxCID(tx){	
	tx.executeSql("SELECT max(id) as id FROM CONTACT",[],LoadMaxCIDSuccess,LoadMaxCIDError);
}
function LoadMaxCIDSuccess(tx,results){
	contactID = results.rows.item(0).id;
}
function LoadMaxCIDError(err){
	alert("Load Max Contact ID Error");
}
// = = = = = = = = = = = = = = = = = = = = Contact List Page  = = = = = = = = = = = = = = = = = = = =
//Load Contact list
function loadContactList(tx){
	tx.executeSql('SELECT id,firstname,lastname FROM CONTACT ORDER BY LOWER(firstname)',[],loadCtListSuccess,loadCtListError);
}
function loadCtListSuccess(tx, results){
	var length = results.rows.length;
	if (length==0) $("#contact_list_status").text("No contact"); else $("#contact_list_status").text("");
	$("#contact_listview").empty();
	for (var i=0; i<length; i++){
		$("#contact_listview").append('<li><a class="contact_list" href="#" contactId="' + 
			results.rows.item(i).id +'" data-transition="pop">' + results.rows.item(i).firstname + ' ' + results.rows.item(i).lastname + '</a></li>').listview('refresh');
	}
	//contact item is clicked
	$(".contact_list").off().on("click",function(){
		contactID = $(this).attr('contactId');
		db.transaction(LoadContact,ErrorDB);
	});
}
function loadCtListError(err){
	alert("Can't load Contact List!\n" + err);
}
// = = = = = = = = = = = = = = = = = = = = Contact Details Page  = = = = = = = = = = = = = = = = = = = =
//Load Contact from the database
function LoadContact(tx){
	tx.executeSql('SELECT * FROM CONTACT WHERE (id=' + contactID + ')',[],LoadCtSuccess,LoadCtError);
}
function LoadCtSuccess(tx, results){
	var res=results.rows.item(0);
	$("#cdt_fname_input").val(res.firstname);
	$("#cdt_lname_input").val(res.lastname);
	$("#cdt_company_input").val(res.company);
	$("#cdt_job_title_input").val(res.jobtitle);
	$("#cdt_business_phone_input").val(res.businessphone);
	$("#cdt_home_phone_input").val(res.homephone);
	$("#cdt_mobile_phone_input").val(res.mobilephone);
	$("#cdt_fax_number_input").val(res.faxnumber);
	$("#cdt_street_input").val(res.street);
	$("#cdt_city_input").val(res.city);
	$("#cdt_state_input").val(res.state);
	$("#cdt_country_input").val(res.country);
	$("#cdt_note_textarea").val(res.note);
	window.location.href= '#contact_details';
	$("#edit_contact_button").off().on("click",function(){
		var res=results.rows.item(0);
		$("#ec_fname_input").val(res.firstname);
		$("#ec_lname_input").val(res.lastname);
		$("#ec_company_input").val(res.company);
		$("#ec_job_title_input").val(res.jobtitle);
		$("#ec_business_phone_input").val(res.businessphone);
		$("#ec_home_phone_input").val(res.homephone);
		$("#ec_mobile_phone_input").val(res.mobilephone);
		$("#ec_fax_number_input").val(res.faxnumber);
		$("#ec_street_input").val(res.street);
		$("#ec_city_input").val(res.city);
		$("#ec_state_input").val(res.state);
		$("#ec_country_input").val(res.country);
		$("#ec_note_textarea").val(res.note);
	});
	$("#save_contact_button").off().on("click",function(){
		db.transaction(SaveContact,SaveContactError,SaveContactSuccess);
	});
	$("#dc_yes_button").off().on("click",function(){
		db.transaction(deleteContact,deleteCtError,deleteCtSuccess);
	});
}
function LoadCtError(err){
	alert("Can't load contact from database\n" +err);
	$("#cdt_fname_input").val("");
	$("#cdt_lname_input").val("");
	$("#cdt_company_input").val("");
	$("#cdt_job_title_input").val("");
	$("#cdt_business_phone_input").val("");
	$("#cdt_home_phone_input").val("");
	$("#cdt_mobile_phone_input").val("");
	$("#cdt_fax_number_input").val("");
	$("#cdt_street_input").val("");
	$("#cdt_city_input").val("");
	$("#cdt_state_input").val("");
	$("#cdt_country_input").val("");
	$("#cdt_note_textarea").val("");
	window.location.href='#contact_list';
}
//Delete Contact
function deleteContact(tx){
	tx.executeSql('DELETE FROM CONTACT WHERE id='+contactID);
	tx.executeSql('DELETE FROM ASSET WHERE owner='+contactID);
}
function deleteCtSuccess(){
	//refresh the contact list
	db.transaction(loadContactList,ErrorDB);
}
function deleteCtError(err){
	alert("Can not delete this Contact");
}
// = = = = = = = = = = = = = = = = = = = = New Asset Page  = = = = = = = = = = = = = = = = = = = =
//Reset the New Asset page
function ResetNewAsset(){
	try{
	$("#na_item_name_input").val("");
	$("#na_item_category_input").val("");
	$("#na_item_manufacturer_input").val("");
	$("#na_item_model_input").val("");
	$("#na_item_acquired_date_input").val('');
	$("#na_item_purchase_price_input").val("");
	$("#na_item_current_value_input").val("");
	$("#na_item_retired_date_input").val('');
	$("#na_asset_comment_history").html('');
	$("#na_item_condition_select").val('Condition 1').selectmenu('refresh',true);
	$("#na_item_location_select").val('Location 1').selectmenu('refresh',true);	
	}catch(e){
	}
}
//Add a new asset to asset list
function addNewAsset(tx){
	tx.executeSql('INSERT INTO ASSET (item,category,manufacturer,model,acquireddate,purchaseprice,currentvalue,condition,location,owner,retireddate,comment)' +
		' VALUES (' +
		'"' + $("#na_item_name_input").val() + '",' +
		'"' + $("#na_item_category_input").val() + '",' +
		'"' + $("#na_item_manufacturer_input").val() + '",' +
		'"' + $("#na_item_model_input").val() + '",' +
		'"' + $("#na_item_acquired_date_input").val() + '",' +
		$("#na_item_purchase_price_input").val() + ',' +
		$("#na_item_current_value_input").val() + ',' +
		'"' + $("#na_item_condition_select").val() + '",' +
		'"' + $("#na_item_location_select").val() + '",' +
		$("#na_item_owner_select").val() + ',' +
		'"' + $("#na_item_retired_date_input").val() + '",' +
		'"' + $("#na_asset_comment_history").html() + '")'
	);
}
function addNewAssetSuccess(){
	$("#ad_item_name_input").val($("#na_item_name_input").val());
	$("#ad_item_category_input").val($("#na_item_category_input").val());
	$("#ad_item_manufacturer_input").val($("#na_item_manufacturer_input").val());
	$("#ad_item_model_input").val($("#na_item_model_input").val());
	$("#ad_item_acquired_date_input").val($("#na_item_acquired_date_input").val());
	$("#ad_item_purchase_price_input").val($("#na_item_purchase_price_input").val());
	$("#ad_item_current_value_input").val($("#na_item_current_value_input").val());
	$("#ad_item_condition_input").val($("#na_item_condition_select").val());
	$("#ad_item_location_input").val($("#na_item_location_select").val());
	$("#ad_item_owner_input").val($("#na_item_owner_select").val());
	$("#ad_item_retired_date_input").val($("#na_item_retired_date_input").val());
	$("#ad_asset_comment_history").html($("#na_asset_comment_history").html());
	
	//Edit Asset Button is clicked
	$("#edit_asset_button").off().on("click",function(){
		editAsset=1;		
		db.transaction(loadOwner,ErrorDB);
		db.transaction(loadMaxAID,ErrorDB);
		
		$("#ea_item_name_input").val($("#ad_item_name_input").val());
		$("#ea_item_category_input").val($("#ad_item_category_input").val());
		$("#ea_item_manufacturer_input").val($("#ad_item_manufacturer_input").val());
		$("#ea_item_model_input").val($("#ad_item_model_input").val());
		$("#ea_item_acquired_date_input").val($("#ad_item_acquired_date_input").val());
		$("#ea_item_purchase_price_input").val($("#ad_item_purchase_price_input").val());
		$("#ea_item_current_value_input").val($("#ad_item_current_value_input").val());
		$("#ea_item_condition_input").val($("#ad_item_condition_input").val());
		$("#ea_item_location_input").val($("#ad_item_location_input").val());
		$("#ea_item_owner_input").val($("#ad_item_owner_input").val());
		$("#ea_item_retired_date_input").val($("#ad_item_retired_date_input").val());
		$("#ea_asset_comment_history").html($("#ad_asset_comment_history").html());
		
		//Save Asset Button is clicked
		$("#save_edit_asset_button").off().on("click",function(){
			db.transaction(SaveAsset,SaveAssetError,SaveAssetSuccess);
			previousNATab = "tab1";
			$("#asset_details_tab").removeClass("ui-screen-hidden");
			$("#asset_comments_tab").addClass("ui-screen-hidden");
		});
		//Cancel Edit Asset Button is clicked
		$("#cancel_edit_asset_button").off().on("click",function(){
			previousNATab = "tab1";
			$("#asset_details_tab").removeClass("ui-screen-hidden");
			$("#asset_comments_tab").addClass("ui-screen-hidden");
		});
		previousNATab = "tab1";
		$("#asset_details_tab").removeClass("ui-screen-hidden");
		$("#asset_comments_tab").addClass("ui-screen-hidden");
	});
	$("#da_yes_button").off().on("click",function(){
		db.transaction(deleteAsset,deleteAssetError,deleteAssetSuccess);
	});
}
function addNewAssetError(err){
	alert("New Asset add failed!\n" + err.message);
}
function loadMaxAID(tx){
	tx.executeSql("SELECT max(id) as id FROM ASSET",[],loadMaxAIDSuccess,loadMaxAIDError);
}
function loadMaxAIDSuccess(tx, results){
	assetID = results.rows.item(0).id;
}
function loadMaxAIDError(err){
	alert("Load Max Asset ID Error");
}
//Load the owner list from the contact list
function loadOwner(tx){
	if (isCreateDbSuccess){
		tx.executeSql('SELECT id,firstname,lastname FROM CONTACT ORDER BY LOWER(firstname)',[],loadOwnerSuccess,loadOwnerError);	
	}
}
function loadOwnerSuccess(tx, results){	
	var length = results.rows.length;
	if (length==0) {
		alert("New Asset: No contact in contact list");
		window.location.href='index.html';
	}
	else {
		if (editAsset==0){
			$("#na_item_owner_select").empty();
			for (var i=0; i<length; i++) {
				$("#na_item_owner_select").append('<option value="'+results.rows.item(i).id+'">' + results.rows.item(i).firstname + ' ' + results.rows.item(i).lastname + '</option>');
				
			}
			$("#na_item_owner_select").selectmenu('refresh');
		} else {
			$("#ea_item_owner_select").empty();
			for (var i=0; i<length; i++) {
				$("#ea_item_owner_select").append('<option value="'+results.rows.item(i).id+'">' + results.rows.item(i).firstname + ' ' + results.rows.item(i).lastname + '</option>');
				
			}
			$("#ea_item_owner_select").selectmenu('refresh');
		}
	}
}
function loadOwnerError(err){
	alert("Can't load owner from database");
	window.location.href='index.html';
}

// = = = = = = = = = = = = = = = = = = = = Asset List Page  = = = = = = = = = = = = = = = = = = = =
//Load Asset list
function loadAssetList(tx){
	tx.executeSql('SELECT id, item FROM ASSET ORDER BY LOWER(item)',[],loadAListSuccess,loadAListError);
}
function loadAListSuccess(tx, results){	
	var length = results.rows.length;
	if (length==0) $("#asset_list_status").text("No asset"); else {
		$("#asset_list_status").text("");
		$("#asset_listview").empty();
		for (var i=0; i<length; i++) {		
			$("#asset_listview").append('<li><a class="item_link" href="#asset_details" assetId="' + results.rows.item(i).id + '" data-transition="pop">' + results.rows.item(i).item + '</a></li>').listview('refresh');
		}
		//Asset item is clicked
		$(".item_link").off().on("click",function(){
			assetID = $(this).attr('assetId');
			db.transaction(loadAssetDetails,ErrorDB);
		});
	}
};
function loadAListError(){
	alert("Can't load Assit List");
}
//Load Asset in the Asset List from database
function loadAssetDetails(tx){
	tx.executeSql('SELECT * FROM ASSET WHERE (id=' + assetID + ')',[],loadADSuccess,loadADError);
}
function loadADSuccess(tx, results){
	var res = results.rows.item(0);	
	$("#ad_item_name_input").val(res.item);
	$("#ad_item_category_input").val(res.category);
	$("#ad_item_manufacturer_input").val(res.manufacturer);
	$("#ad_item_model_input").val(res.model);
	$("#ad_item_acquired_date_input").val(res.acquireddate);
	$("#ad_item_purchase_price_input").val(res.purchaseprice);
	$("#ad_item_current_value_input").val(res.currentvalue);
	$("#ad_item_condition_input").val(res.condition);
	$("#ad_item_location_input").val(res.location);
	$("#ad_item_owner_input").val(res.owner);
	$("#ad_item_retired_date_input").val(res.retireddate);
	$("#ad_asset_comment_history").html(res.comment);
	//Swap between Details tab and Comments tab	
	previousNATab = 'tab1';
	$("#new_asset_navbar ul li").off().on("click",function(){
		var newNATab = $(this).children("a").attr("data-tab-class");
		$("."+previousNATab).addClass("ui-screen-hidden");
		$("."+newNATab).removeClass("ui-screen-hidden");	
		previousNATab = newNATab;
	});
	$("#edit_asset_button").off().on("click",function(){
		editAsset=1;
		db.transaction(loadOwner,ErrorDB);
		
		$("#ea_item_name_input").val(res.item);
		$("#ea_item_category_input").val(res.category);
		$("#ea_item_manufacturer_input").val(res.manufacturer);
		$("#ea_item_model_input").val(res.model);
		$("#ea_item_acquired_date_input").val(res.acquireddate);
		$("#ea_item_purchase_price_input").val(res.purchaseprice);
		$("#ea_item_current_value_input").val(res.currentvalue);
		$("#ea_item_condition_select").val(res.condition);
		$("#ea_item_location_select").val(res.location);
		$("#ea_item_owner_select").val(res.owner);
		$("#ea_item_retired_date_input").val(res.retireddate);
		$("#ea_asset_comment_history").html(res.comment);
		
		//Save Asset Button is clicked
		$("#save_edit_asset_button").off().on("click",function(){
			db.transaction(SaveAsset,SaveAssetError,SaveAssetSuccess);
		});
		//Cancel Edit Asset Button is clicked
		$("#cancel_edit_asset_button").off().on("click",function(){
			
		});
	});
	$("#da_yes_button").off().on("click",function(){
		db.transaction(deleteAsset,deleteAssetError,deleteAssetSuccess);
	});
}
function loadADError(err){
	alert("Load Asset Error\n" + err);
	window.location.href='#asset_list';
}
//Save Asset
function SaveAsset(tx){
	tx.executeSql('UPDATE ASSET SET item="' + $("#ea_item_name_input").val() + '",'
		+ ' category="' + $("#ea_item_category_input").val() + '",'
		+ ' manufacturer="' + $("#ea_item_manufacturer_input").val() + '",'
		+ ' model="' + $("#ea_item_model_input").val() + '",'
		+ ' acquireddate="' + $("#ea_item_acquired_date_input").val() + '",'
		+ ' purchaseprice=' + $("#ea_item_purchase_price_input").val() + ','
		+ ' currentvalue=' + $("#ea_item_current_value_input").val() + ','
		+ ' condition="' + $("#ea_item_condition_select").val() + '",'
		+ ' location="' + $("#ea_item_location_select").val() + '",'
		+ ' owner=' + $("#ea_item_owner_select").val() + ','
		+ ' retireddate="' + $("#ea_item_retired_date_input").val() + '",'
		+ ' comment="' + $("#ea_asset_comment_history").html() + '"'
		+ ' WHERE id=' + assetID);
	
	$("#ad_item_name_input").val($("#ea_item_name_input").val());
	$("#ad_item_category_input").val($("#ea_item_category_input").val());
	$("#ad_item_manufacturer_input").val($("#ea_item_manufacturer_input").val());
	$("#ad_item_model_input").val($("#ea_item_model_input").val());
	$("#ad_item_acquired_date_input").val($("#ea_item_acquired_date_input").val());
	$("#ad_item_purchase_price_input").val($("#ea_item_purchase_price_input").val());
	$("#ad_item_current_value_input").val($("#ea_item_current_value_input").val());
	$("#ad_item_condition_input").val($("#ea_item_condition_select").val());
	$("#ad_item_location_input").val($("#ea_item_location_select").val());
	$("#ad_item_owner_input").val($("#ea_item_owner_select").val());
	$("#ad_item_retired_date_input").val($("#ea_item_retired_date_input").val());
	$("#ad_asset_comment_history").html($("#ea_asset_comment_history").html());
}
function SaveAssetSuccess(){
	
}
function SaveAssetError(err){
	alert("Saving Asset Failed\n" + err.message)
}
//Save Contact
function SaveContact(tx){
	tx.executeSql('UPDATE CONTACT SET firstname ="' + $("#ec_fname_input").val() + '",'
		+ ' lastname="' + $("#ec_lname_input").val() + '",'
		+ ' company="' + $("#ec_company_input").val() + '",'
		+ ' jobtitle="' + $("#ec_job_title_input").val() + '",'
		+ ' businessphone="' + $("#ec_business_phone_input").val() + '",'
		+ ' homephone="' + $("#ec_home_phone_input").val() + '",'
		+ ' mobilephone="' + $("#ec_mobile_phone_input").val() + '",'
		+ ' faxnumber="' + $("#ec_fax_number_input").val() + '",'
		+ ' street="' + $("#ec_street_input").val() + '",'
		+ ' city="' + $("#ec_city_input").val() + '",' 
		+ ' state="' + $("#ec_state_input").val() + '",'
		+ ' country="' + $("#ec_country_input").val() + '",'
		+ ' note="' + $("#ec_note_textarea").val() + '"'
		+ ' WHERE id=' + contactID);
		
	$("#cdt_fname_input").val($("#ec_fname_input").val());
	$("#cdt_lname_input").val($("#ec_lname_input").val());
	$("#cdt_company_input").val($("#ec_company_input").val());
	$("#cdt_job_title_input").val($("#ec_job_title_input").val());
	$("#cdt_business_phone_input").val($("#ec_business_phone_input").val());
	$("#cdt_home_phone_input").val($("#ec_home_phone_input").val());
	$("#cdt_mobile_phone_input").val($("#ec_mobile_phone_input").val());
	$("#cdt_fax_number_input").val($("#ec_fax_number_input").val());
	$("#cdt_street_input").val($("#ec_street_input").val());
	$("#cdt_city_input").val($("#ec_city_input").val());
	$("#cdt_state_input").val($("#ec_state_input").val());
	$("#cdt_country_input").val($("#ec_country_input").val());
	$("#cdt_note_textarea").val($("#ec_note_textarea").val());	
}
function SaveContactError(err){
	alert("Saving Contact Error" + err.message);
}
function SaveContactSuccess(){
}
//Delete Asset
function deleteAsset(tx){
	tx.executeSql('DELETE FROM ASSET WHERE id='+assetID);
}
function deleteAssetError(err){
	alert("Can not delete this asset");
}
function deleteAssetSuccess(){
	db.transaction(loadAssetList,ErrorDB);
}
// = = = = = = = = = = = = = = = = = = = = Asset Report Page  = = = = = = = = = = = = = = = = = = = =
function loadReport(tx){
	tx.executeSql('SELECT id,item,category,location,owner,retireddate FROM ASSET ORDER BY '+ groupBy,[],loadReportSuccess,loadReportError);
}
function loadReportError(err){
	alert("Can't load report from database");
}
function loadReportSuccess(tx,results){
	var length = results.rows.length;
	var group="";
	$("#report_listview").empty();
	if (groupBy=="category"){	
		for (var i=0; i<length; i++){
			if (group!=results.rows.item(i).category){
				$("#report_listview").append('<li data-role="list-divider">' + results.rows.item(i).category + '</li>');
				group=results.rows.item(i).category;
			}
			$("#report_listview").append('<li><a href="#asset_details" class="asset_item" assetId="' + results.rows.item(i).id +'" data-transition="pop">' + results.rows.item(i).item + '</a></li>');
		}
	}
	else if (groupBy=="location"){
		for (var i=0; i<length; i++){
			if (group!=results.rows.item(i).location){
				$("#report_listview").append('<li data-role="list-divider">' + results.rows.item(i).location + '</li>');
				group=results.rows.item(i).location;
			}
			$("#report_listview").append('<li><a href="#asset_details" class="asset_item" assetId="' + results.rows.item(i).id +'" data-transition="pop">' + results.rows.item(i).item + '</a></li>');
		}
	}
	else if (groupBy=="owner"){
		for (var i=0; i<length; i++){
			if (group!=results.rows.item(i).owner){
				$("#report_listview").append('<li data-role="list-divider">' + results.rows.item(i).owner + '</li>');
				group=results.rows.item(i).owner;
			}
			$("#report_listview").append('<li><a href="#asset_details" class="asset_item" assetId="' + results.rows.item(i).id +'" data-transition="pop">' + results.rows.item(i).item + '</a></li>');
		}
	}
	else {
		for (var i=0; i<length; i++){
			if (group!=results.rows.item(i).retireddate){
				$("#report_listview").append('<li data-role="list-divider">' + results.rows.item(i).retireddate + '</li>');
				group=results.rows.item(i).retireddate;
			}
			$("#report_listview").append('<li><a href="#asset_details" class="asset_item" assetId="' + results.rows.item(i).id +'" data-transition="pop">' + results.rows.item(i).item + '</a></li>');
		}
	}
	$("#report_listview").listview('refresh');
	//Report Group changed	
	$("#report_group_select").change(function(){
		groupBy = $("select#report_group_select option:selected").val();
		$("#report_group_select").val(groupBy);
		db.transaction(loadReport,ErrorDB);
	});
	//Asset item is clicked
	$(".asset_item").off().on("click",function(){
		assetID = $(this).attr('assetId');
		db.transaction(loadAssetDetails,ErrorDB);
	});
}

